﻿/*
 * timedcumulantmonitor.cpp
 *
 *  Created on: 2017年4月15日
 *      Author: work
 */

#include <dm/export.hpp>

#define DM_API_SCADA DM_API_EXPORT

#include <dm/scada/timedcumulantmonitor.hpp>
#include <dm/scada/cumulantmgr.hpp>
#include <dm/scada/devicemgr.hpp>
#include <dm/datetime.hpp>

#include <iostream>

using namespace std;

namespace dm{
namespace scada{

CTimedCumulantMonitor::CTimedCumulantMonitor():m_mgr(CTimedCumulantMgr::ins()),m_p(m_mgr.m_q->getCurPos()){
}

CTimedCumulantMonitor::CTimedCumulantMonitor( const ringpos_t* p ):m_mgr(CTimedCumulantMgr::ins()){
	m_p = *p;
}

CTimedCumulantMonitor::~CTimedCumulantMonitor(){
}

void CTimedCumulantMonitor::onNew( const ringpos_t& pos,const CTimedCumulant& info,const bool& overFlow )const{
	const dm::CTimeStamp& ts = info.getTimeStamp();
	dm::CDateTime dt(ts);

	cout <<pos.getCycle()<<"."<<pos.getPos()<<'['<<ts.seconds()<<'.'<<ts.mseconds()<<' '<<dt.toString().c_str()<<']';
	if( overFlow )
		cout <<"(of)";

	CCumulantMgr& mgr = CCumulantMgr::ins();

	cout << CDeviceMgr::ins().desc(mgr.deviceIndex(info.getIndex()))<<'.'<<mgr.desc(info.getIndex())<<"(id="<<mgr.id(info.getIndex())
			<<",name="<<mgr.name(info.getIndex()) <<") raw="
			<<info.getRaw()<<" value="<< mgr.calcValue(info.getIndex(),info.getRaw()) <<endl;
}

bool CTimedCumulantMonitor::filter( const ringpos_t& /*pos*/,const CTimedCumulant& /*info*/,const bool& /*overflow*/ )const{
	return false;
}

void CTimedCumulantMonitor::run(){
	CTimedCumulant info;
	bool overflow;

	while( true ){
		if( m_mgr.m_q->waitAndCheckOver(m_p,overflow,info,1) )
			continue;
		if( !filter(m_p,info,overflow) )
			onNew(m_p,info,overflow);
		if( overflow )
			m_p = m_mgr.m_q->getCurPos();
	}
}

bool CTimedCumulantMonitor::tryGet( CTimedCumulant& info,bool& overflow ){
	return m_mgr.m_q->popAndCheckOver( m_p,overflow,info);
}

void CTimedCumulantMonitor::get( CTimedCumulant& info,bool& overflow ){
	m_mgr.m_q->waitAndCheckOver( m_p,overflow,info);
}

void CTimedCumulantMonitor::reset(){
	m_p = m_mgr.m_q->getCurPos();
}

}
}


